package com.maikobi.maikobi.controller;

import com.maikobi.maikobi.manager.AiManager;
import com.maikobi.maikobi.model.entity.Chart;
import com.maikobi.maikobi.model.enums.ChartStatus;
import com.maikobi.maikobi.service.ChartService;
import com.maikobi.maikobi.task.ChartGenerateTask;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * @author: Maiko7
 * @create: 2025-07-16 10:46
 */
@Slf4j
@RestController
public class ChartController {

    @Resource
    private ChartService chartService;

    // 假设你在某个业务类方法中：
    public void submitChartTask(Chart chart, Long biModelId, String userInput,
                                ChartService chartService, AiManager aiManager,
                                ExecutorService chartThreadPool) {
        ChartGenerateTask task = new ChartGenerateTask(chart, biModelId, userInput, chartService, aiManager);
        CompletableFuture
                .runAsync(task, chartThreadPool)
                .thenRun(() -> {
                    // 成功后的后置处理逻辑（可选）
                    log.info("图表任务执行成功：chartId={}", task.getChart().getId());
                })
                .exceptionally(ex -> {
                    // 异常处理逻辑（记录异常并更新数据库）
                    log.error("图表任务执行异常：chartId={}，错误信息={}", task.getChart().getId(), ex.getMessage(), ex);
                    handleChartUpdateError(task.getChart().getId(), "任务执行异常：" + ex.getMessage());
                    return null;
                });

    }

    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ChartStatus.FAILED);
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + chartId + "," + execMessage);
        }
    }
}
